package angels.client.Tasks;
import java.net.HttpURLConnection;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import angels.client.Entities.Categories;
import angels.client.Entities.Categories.Type;
import angels.client.Helpers.JSONHelper;
import angels.client.Listeners.MainMenuListener;
import angels.client.Services.BusyHourService;

public class GetCategoriesTask extends TimerTask {
	private DefaultHttpClient client;
	private final BusyHourService service;
	private final MainMenuListener listener;
	private final Type type;
	private final String selectedCategory;
	
	public GetCategoriesTask(BusyHourService service,MainMenuListener listener, Type type,String selectedCategory) {
		this.service = service;
		this.listener=listener;
		this.type=type;
		this.selectedCategory=selectedCategory;
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        client = new DefaultHttpClient(httpParameters);
	}
	
	@Override
    public void run() {
		try {
			String path=service.getCategoryURL(type,selectedCategory);
			HttpGet request = new HttpGet(path);
			HttpResponse response = client.execute(request);
			
			if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK)
			{
				listener.onCategoriesReceivedError();
			    return;
			}
			
			JSONObject json_response;
						
			Categories categories=null;
						
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
				json_response = JSONHelper.parseJSONResponse(response);
				categories=new Categories(json_response,type);
			} 
			if (categories!=null){
				listener.onCategoriesReceived(categories);
			}
		} catch (Exception e) {e.printStackTrace();}
	}
}